package com.common.servlet.abstracts;

import java.util.List;

import com.common.model.abstracts.AbstractJSON;
import com.common.model.abstracts.AbstractResponse;
import com.common.security.abstracts.AbstractError;
import com.common.security.exceptions.ParserException;
import com.common.servlet.util.JSONProtocolBase;

public abstract class AbstractJSONParser {

	public String parseError(AbstractError error) {
		StringBuilder builder = new StringBuilder();

		builder.append(JSONProtocolBase.OPEN_TAG);
		builder.append(JSONProtocolBase.ERROR_TAG);
		builder.append(JSONProtocolBase.OPEN_TAG);
		builder.append(JSONProtocolBase.MESSAGE_TAG);
		builder.append(valueToString(error.getMessage()));
		builder.append(JSONProtocolBase.NEW_PARAMETER);
		builder.append(JSONProtocolBase.CODE_TAG);
		builder.append(error.getCode());
		builder.append(JSONProtocolBase.CLOSE_TAG);
		builder.append(JSONProtocolBase.CLOSE_TAG);

		return builder.toString();
	}

	public abstract String parseResponse(AbstractResponse abstractResponse)
			throws ParserException;

	protected String valueToString(String value) {
		return JSONProtocolBase.STRING + value + JSONProtocolBase.STRING;
	}
	
	protected String valueToString(Object object) {
		return JSONProtocolBase.STRING + object.toString() + JSONProtocolBase.STRING;
	}

	protected String valueToObject(AbstractJSON object) {
		return escapeJSON(object.toJSON());
	}

	protected String valueToArray(List<? extends AbstractJSON> items) {
		StringBuilder builder = new StringBuilder();

		builder.append(JSONProtocolBase.OPEN_ARRAY);
		for (int i = 0; i < items.size(); i++) {
			builder.append(items.get(i).toJSON());

			if (i + 1 < items.size()) {
				builder.append(JSONProtocolBase.NEW_PARAMETER);
			}
		}
		builder.append(JSONProtocolBase.CLOSE_ARRAY);

		return builder.toString();
	}
	
	/**
	 * Escape JSON special characters:
	 * 
	 * New Line
	 */
	private String escapeJSON(String value) {
		return value.replace("\n", "\\n");
	}
}
